package org.yuci.concurency.interrupt.case03;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * http://tutorials.jenkov.com/java-util-concurrent/executorservice.html
 *
 */
public class ExecutorTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(1);

        Future<String> future = executorService.submit(new Callable<String>() {
            public String call() {
                getStuck();
                return "done";
            }
            
            private void getStuck() {
                while (true) {
                    if (Thread.currentThread().isInterrupted()) {
                        System.out.println("I'm interrupted.");
                        break;
                    }
                    
                    System.out.println("I'm stuck.");
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        System.out.println("I'm interrupted: " + e.getMessage());
                        break;
                    }                    
                }
            }
            
            
        });

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e1) {
            System.out.println("Master: not able to sleep.");
        }
        executorService.shutdownNow();
        System.out.println("Executor service shut down.");
        
        boolean ret = false;
        try {
            ret = executorService.awaitTermination(5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            System.out.println("InterruptedException: " + e.getMessage());
        }
        System.out.println("awaitTermination? " + ret);
        
        String str = null;
        try {
            str = future.get(5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            System.out.println("InterruptedException: " + e.getMessage());
        } catch (ExecutionException e) {
            System.out.println("ExecutionException: " + e.getMessage());
        } catch (TimeoutException e) {
            System.out.println("TimeoutException: " + e.getMessage());
        }
        System.out.println("future.get()? " + str);
    }

}
